package com.yycx.module.bus.provider.handler.invoice;

import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.constants.CommonConstants;
import com.yycx.common.mybatis.interceptor.SaveInterceptor;
import com.yycx.common.mybatis.query.CriteriaSave;
import com.yycx.common.security.OpenHelper;
import com.yycx.common.utils.ApiAssert;
import com.yycx.common.utils.OrderNoUtil;
import com.yycx.groovy.provider.script.MyGroovyScriptEngine;
import com.yycx.module.bus.client.entity.BusOrder;
import com.yycx.module.bus.client.entity.BusOrderDetails;
import com.yycx.module.bus.client.entity.BusPayment;
import com.yycx.module.bus.client.entity.BusSupplier;
import com.yycx.module.bus.client.enums.AmountTypeEnum;
import com.yycx.module.bus.provider.service.BusOrderDetailsService;
import com.yycx.module.bus.provider.service.BusOrderService;
import com.yycx.module.bus.provider.service.BusSupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 开票税金保存扩展器
 *
 * @author zyf
 */
@Component("invoicePaymentSaveHandler2")
public class InvoicePaymentSaveHandler2 implements SaveInterceptor<BusPayment> {

    @Autowired
    private MyGroovyScriptEngine groovyScriptEngine;
    @Resource
    private OrderNoUtil orderNoUtil;

    @Autowired
    private BusSupplierService supplierService;


    @Autowired
    private BusOrderService orderService;

    @Resource
    private BusOrderDetailsService orderDetailsService;


    @Override
    public void prepare(CriteriaSave cs, EntityMap entityMap, BusPayment payment) {
        String selectIds = cs.getParams("selectIds");
        ApiAssert.isNotEmpty("开票明细不能为空", selectIds);
        Long supplierId = payment.getSupplierId();
        ApiAssert.isNotEmpty("supplierId不能为空", supplierId);
        Long invoiceUnitId = payment.getInvoiceUnitId();
        ApiAssert.isNotEmpty("invoiceUnitId不能为空", invoiceUnitId);
        String amountFormulaContent = cs.getParams("amountFormulaContent");
        String yfSupplierRetable = cs.getParams("yfSupplierRetable");
        String invoiceAmount = cs.getParams("invoiceAmount2");
        BusSupplier supplier = supplierService.getById(supplierId);
        //应返金额
        String[] selectIdsArray = selectIds.split(",");
        if (selectIdsArray.length == 1) {
            BusOrderDetails orderDetails = orderDetailsService.getById(selectIdsArray[0]);
            BusOrder order = orderService.getById(orderDetails.getOrderId());
            payment.setOrderId(order.getOrderId().toString());
            payment.setDeptId(order.getDeptId());
            payment.setOrderDetailsId(orderDetails.getOrderDetailsId().toString());
            payment.setCustomId(order.getCustomId().toString());
        }
        payment.setTitle("开票税金");

        BigDecimal supplierRetableTotal = new BigDecimal("0");
        BigDecimal invoiceAmountTotal = new BigDecimal("0");
        BigDecimal invoiceSj = new BigDecimal("0");
        if (FlymeUtils.isNotEmpty(yfSupplierRetable)) {
            String[] supplierRetableArray = yfSupplierRetable.split("#");
            for (String s : supplierRetableArray) {
                BigDecimal amount = new BigDecimal(s);
                supplierRetableTotal = supplierRetableTotal.add(amount);
            }
        }
        if (FlymeUtils.isNotEmpty(invoiceAmount)) {
            String[] invoiceAmountArray = invoiceAmount.split("#");
            for (String s : invoiceAmountArray) {
                BigDecimal amount = new BigDecimal(s);
                invoiceAmountTotal = invoiceAmountTotal.add(amount);
                BigDecimal taxAmount = calculateTaxAmount(amount, amountFormulaContent);
                invoiceSj = invoiceSj.add(taxAmount);
            }
        }
        payment.setInvoiceAmount(invoiceAmountTotal);
        payment.setSupplierRetable(supplierRetableTotal);
        payment.setAmount(invoiceSj);
        //给真奥返款对应supplierRetable2
        payment.setSettleType(2);
        payment.setAmountType(AmountTypeEnum.Invoice.getCode());
        String orderNo = orderNoUtil.getIncrementNum();
        payment.setPaymentNo("SJ" + orderNo);
        payment.setOrganizationId(supplier.getOrganizationId());
        payment.setCompanyId(supplier.getCompanyId());
        payment.setSupplierId(supplier.getSupplierId());
        payment.setUserId(OpenHelper.getUserId());
        payment.setNickName(OpenHelper.getNickName());
        payment.setPaymentState(CommonConstants.INT_0);
    }

    @Override
    public void complete(CriteriaSave cs, EntityMap params, BusPayment entity) {
        String selectIds = cs.getParams("selectIds");
        //关联开票ID
        orderDetailsService.updateKaipiaoId2(entity, selectIds);
    }

    /**
     * 计算开票税金
     *
     * @param invoiceAmount
     * @return
     */
    private BigDecimal calculateTaxAmount(BigDecimal invoiceAmount, String amountFormulaContent) {
        BigDecimal taxAmount = new BigDecimal("0");
        ApiAssert.isNotEmpty("税金公式不能为空", amountFormulaContent);
        try {
            Map<String, Object> variable = new HashMap<>();
            variable.put("开票金额", invoiceAmount);
            taxAmount = groovyScriptEngine.executeBigDecimal(amountFormulaContent, variable,2);
        } catch (Exception e) {
            e.printStackTrace();
            ApiAssert.failure("开票税金计算异常");
        }
        return taxAmount;
    }

}
